from db import utils
from logger import logger
from sub_events.base_event import BaseEvent

LOGGER = logger.CustomLogger()


class CheckMultiThreadMappingEvent(BaseEvent):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.event_name_zh: str = "多线程映射检查"
        self.event_name_en: str = "Multi-Thread Mapping Check"

    def pre_execute(self):
        """检查是否需要执行多线程映射检查"""
        # 先获取修改了哪些文件，然后在查询这些文件是否有包含在normal_file中的
        file_list = self.git_client.get_filenames(self.hook.pr_number, params={'access_token': self.get_admin_token()})
        for filename in file_list:
            if filename in self.MAPPING_CHECKER.mapping_normal_file:
                LOGGER.info(f"[{self.hook.pr_number}] found modified file {filename} in multi-thread mapping normal_file")
                return True
        return False

    def execute(self):
        """执行多线程映射检查"""
        LOGGER.info(f"[{self.hook.pr_number}] start multi-thread mapping check")
        force_status = utils.get_force_pass_status_by_hook(self.hook, "mtm")
        if force_status:
            LOGGER.info(f"[{self.hook.pr_number}] multi-thread mapping check is force passed by {force_status['commenter']}")
            return
        try:
            diff_info = self.git_client.get_diff_info(self.hook.pr_number, self.get_admin_token())
            # 执行检查动作
            missing_info = self.MAPPING_CHECKER.run(diff_info)
            if len(missing_info['missing']) == 0:
                self.failed = False
            else:
                self.failed = True
                suggestion = "多线程映射检查未通过，以下多线程API缺少映射信息，请补充后重新提交：\n\n"
                suggestion += "\nMulti-Thread Mapping Check failed. The following multi-thread APIs are missing mapping information, please supplement and resubmit:\n\n"
                for api in missing_info['missing']:
                    suggestion += f"- {api['normal_key']}#{api['required_multi_symbol']}\n"
                self.comment = suggestion
                LOGGER.info(f"[{self.hook.pr_number}] multi-thread mapping check failed, missing info: {missing_info['missing']}")
                return
                
        except Exception as e:
            LOGGER.error(f"[{self.hook.pr_number}] multi-thread mapping check failed, details: {str(e)}")
            self.failed = False
            return
